var fs = require('fs');
var http =  require('http');
var path = require('path');
var url = require('url');

var root = process.cwd();

http.createServer(function(req,res) {
  var pathname = url.parse(req.url).pathname;
  var filePath = path.join(root, pathname);

  /**
  * 简单错误处理
  *
  var stream = fs.createReadStream(filePath);
  stream.pipe(res);
  stream.on('error',function(err){
    res.statusCode = 500;
    res.end('Internal Server Error')
  });

  */

  fs.stat(filePath,function(err,stats){
    if(err){
      if(err.code = 'ENOENT'){   // 没有找到文件
        res.statueCode = 404;
        res.end('NOT FOUND');
      }else{
        res.statusCode = 500;
        res.end('Internal Server Error');
      }
    }else{
      var stream = fs.createReadStream(filePath);
      stream.pipe(res);
      stream.on('error',function(err){
        res.statusCode = 500;
        res.end('Internal Server Error');
      });
    }
  });

}).listen(9000);

console.log('Your server is started @9000');
